package networking.udp;

/*
 * Comparing TCP and UDP in java:
 * 
 * TCP:
 * TCP is stream based. you never specify the size of the data you want to send or receive.
 * TCP is stream based thus uses socket's input and output streams.
 * TCP sockets should bind to the addresses when they are being created.
 * 
 * UDP:
 * In UDP however you specify the size of the data you want to send and receive in Bytes.
 * UDP however is DataGram based and uses DatagramSocket and DatagramPacket.
 * UDP sockets are free of addresses, except the server. you only specify the addresses in the packet you are sending. 
 * 
 * Based on what I have seen in c and java languages these rules apply every where.
 *  
 */

/* In this code server sends a message to the client.
 * However for this to be done, the server should know about the address of the client. But this is impossible unless
 * the client sends a Datagram packet to the server. 
 * Thus it is essential for the client to send a packet to the server first.
 */

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

import networking.config.parser.Node;

public class UdpClientServer {

	public static void createClientSocket(Node clientNode, Node serverNode) {
		try {
			DatagramSocket cllientSocket = new DatagramSocket();
			clientNode.setUdpClientSocket(cllientSocket);

		} catch (SocketException e) {
			e.printStackTrace();
		}

	}

	public static void createServerSocket(Node serverNode) {
		try {
			DatagramSocket serverSocket = new DatagramSocket(serverNode.getPort(), InetAddress.getByName(serverNode.getIp()));
			serverNode.setUdpServerSocket(serverSocket);

		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	public static void sendPacket(String ip, int port, DatagramSocket socket) {

		byte[] buf = new byte[256];
		String message = "Parisa";
		buf = message.getBytes();

		DatagramPacket packet;

		try {
			packet = new DatagramPacket(buf, buf.length, InetAddress.getByName(ip), port);
			try {
				socket.send(packet);
				System.out.println(new String(packet.getData()));
			} catch (IOException e) {
				e.printStackTrace();
			}
		} catch (UnknownHostException e1) {
			e1.printStackTrace();
		}
	}

	public static void recvPacket(DatagramSocket socket) {

		byte[] buf = new byte[256];
		DatagramPacket packet = new DatagramPacket(buf, buf.length);

		try {
			socket.receive(packet);
			System.out.println(new String(packet.getData()));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
